<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
   /*
   |--------------------------------------------------------------------------
   | Login Controller
   |--------------------------------------------------------------------------
   |
   | This controller handles authenticating users for the application and
   | redirecting them to your home screen. The controller uses a trait
   | to conveniently provide its functionality to your applications.
   |
   */

   use AuthenticatesUsers;

   /**
    * Where to redirect users after login / registration.
    *
    * @var string
    */
   protected $redirectTo = '/admin';
   protected $username;
   // 单位时间内最大登录尝试次数
   protected $maxAttempts = 3;
   // 单位时间值
   protected $decayMinutes = 30;

   /**
    * 用户名登陆
    */
   public function username()
   {
      return 'name';
   }

   /**
    * 多字段登录并判断状态
    */
   public function attemptLogin(Request $request)
   {
      $username = $request->input('name');
      $password = $request->input('password');
      $status = 1;

      // 验证用户名登录方式
      $usernameLogin = $this->guard()->attempt(
         ['name' => $username, 'password' => $password, 'status' => $status], $request->has('remember')
      );
      if ($usernameLogin) {
         return true;
      }
      // 验证手机号登录方式
      $mobileLogin = $this->guard()->attempt(
         ['phone' => $username, 'password' => $password, 'status' => $status], $request->has('remember')
      );
      if ($mobileLogin) {
         return true;
      }
      // 验证邮箱登录方式
      $emailLogin = $this->guard()->attempt(
         ['email' => $username, 'password' => $password, 'status' => $status], $request->has('remember')
      );
      if ($emailLogin) {
         return true;
      }
      return false;
   }

   /**
    * Create a new controller instance.
    * @return void
    */
   public function __construct()
   {
      $this->middleware('guest:admin', ['except' => 'logout']);
   }

   /**
    * 重写登录视图页面
    */
   public function showLoginForm()
   {
      return view('admin.login');
   }

   /**
    * 退出到登录页面
    */
   public function logout(Request $request)
   {
      $this->guard()->logout();
      $request->session()->invalidate();
      return redirect('/admin/login');
   }

   /**
    * 验证登录
    */
   protected function validateLogin(Request $request)
   {
      $this->validate($request, [
         $this->username() => 'required|string',
         'password' => 'required|string',
         'captcha' => 'required|captcha',
      ]);
   }

   /**
    * 自定义认证驱动
    */
   protected function guard()
   {
      return auth()->guard('admin');
   }
}